package com.zxj.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zxj.common.core.contains.Constants;
import com.zxj.common.core.domain.vo.PageVO;
import com.zxj.common.core.enums.ResultCode;
import com.zxj.common.security.exception.ServiceException;
import com.zxj.friend.domain.question.dto.QuestionPageQueryDTO;
import com.zxj.friend.domain.question.entity.Question;
import com.zxj.friend.domain.question.es.QuestionES;
import com.zxj.friend.domain.question.vo.QuestionDetailVO;
import com.zxj.friend.domain.question.vo.QuestionVO;
import com.zxj.friend.elasticsearch.QuestionRepository;
import com.zxj.friend.manager.QuestionCacheManager;
import com.zxj.friend.mapper.question.QuestionMapper;
import com.zxj.friend.mapper.user.UserSubmitMapper;
import com.zxj.friend.service.question.IQuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxj2022
 * @date 2024/12/26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    private final QuestionRepository questionRepository;

    private final QuestionCacheManager questionCacheManager;

    private final UserSubmitMapper userSubmitMapper;

    /**
     * 分页查询问题列表
     * @param questionPageQueryDTO 分页查询条件
     * @return 问题列表
     */
    @Override
    public PageVO<QuestionVO> pageList(QuestionPageQueryDTO questionPageQueryDTO) {
        // 查询ES中的问题数量
        long count = questionRepository.count();
        if (count <= 0) {
            // ES中的问题数量为0，刷新问题
            refreshQuestion();
        }
        // 构建分页查询条件
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); // 按照创建时间降序排序
        Pageable pageable = PageRequest.of(questionPageQueryDTO.getPageNo() - 1, questionPageQueryDTO.getPageSize(), sort);
        // 获取查询条件
        Integer difficulty = questionPageQueryDTO.getDifficulty();
        String keyword = questionPageQueryDTO.getKeyword();
        Page<QuestionES> questionESPage; // 存储查询结果
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            // 如果难度和关键字都为空，查询所有问题
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            // 如果关键字为空，根据难度查询问题
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            // 如果难度为空，根据关键字查询问题
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            // 根据关键字和难度查询问题
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        // 解析查询结果
        long total = questionESPage.getTotalElements(); // 总数
        if (total <= 0) { // 如果总数为0，直接返回空
            return PageVO.empty();
        }

        List<QuestionES> questionESList = questionESPage.getContent(); // 查询结果
        // 封装查询结果返回
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return PageVO.of(questionVOList, total);
    }

    /**
     * 查询问题详情
     * @param questionId 问题ID
     * @return 问题详情
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = this.getById(questionId);
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    /**
     * 获取上一题
     * @param questionId 问题ID
     * @return 上一题ID
     */
    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    /**
     * 获取下一题
     * @param questionId 问题ID
     * @return 下一题ID
     */
    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    /**
     * 查询热门题目列表
     * @return 热门题目列表
     */
    @Override
    public List<QuestionVO> hotList() {
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <= 0) { // 如果热门题目列表为空
            // 查询热门题目列表, 默认查询热门题目列表的前5个
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        } else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    /**
     * 将数据库中的问题刷新到ES中
     */
    private void refreshQuestion() {
        // 查询数据库中的所有问题
        List<Question> questionList = this.list();
        if (CollectionUtil.isEmpty(questionList)) {
            // 问题列表为空，直接返回
            return;
        }
        // 将问题列表转换为ES中的问题列表
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        // 保存到ES中
        questionRepository.saveAll(questionESList);
    }

    /**
     * 组装问题VO列表
     * @param hotQuestionIdList 热门问题ID列表
     * @return 问题VO列表
     */
    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return new ArrayList<>();
        }
        List<QuestionVO> resultList = new ArrayList<>();
        for (Long questionId : hotQuestionIdList) {
            QuestionVO questionVO = new QuestionVO();
            QuestionDetailVO detail = this.detail(questionId);
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }
}
